package kinect.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;

import dll_test.KinectHandler;


/**
 * Servlet implementation class GetImageFrameServlet
 */
@WebServlet("/GetImageFrameServlet")
public class GetImageFrameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static KinectHandler kHandle = KinectHandler.getInstance();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetImageFrameServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(!kHandle.isInitiated()) kHandle.init();
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		System.out.println("get request from:" + request.getRemoteAddr() + ": " + request.getRemotePort() + "at" + dateFormat.format(date));
		response.setContentType("image/jpg");
		ServletOutputStream out = response.getOutputStream();
		kHandle.updateImageFrame();
		BufferedImage img = kHandle.getImageFrameInBufferedImage();
		JPEGEncodeParam param = JPEGCodec.getDefaultJPEGEncodeParam(img);
		JPEGCodec.createJPEGEncoder(out, param).encode(img, param);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
